export function convertJsonToNodes(json, prefix, parentId = null, position = { x: 0, y: 0 }) {
  const nodes = [];
  let currentY = position.y;

  function processValue(key, value, currentX) {
    const id = parentId ? `${parentId}.${key}` : `${prefix}.${key}`;
    
    // 处理 null 值
    if (value === null) {
      nodes.push({
        id,
        type: 'default',
        data: { label: `${key}: null` },
        position: { x: currentX, y: currentY },
        style: getNodeStyle('null')
      });
      currentY += 50;
      return;
    }

    // 处理数组
    if (Array.isArray(value)) {
      const arrayNode = {
        id,
        type: 'default',
        data: { label: `${key} []` },
        position: { x: currentX, y: currentY },
        style: getNodeStyle('array')
      };
      nodes.push(arrayNode);
      
      // 处理数组的第一个元素作为示例
      if (value.length > 0) {
        const childNodes = convertJsonToNodes(
          { '0': value[0] }, // 将第一个元素转换为对象形式
          prefix,
          id,
          { x: currentX + 200, y: currentY }
        );
        nodes.push(...childNodes);
      }
      currentY += 100;
      return;
    }

    // 处理对象
    if (typeof value === 'object') {
      const objectNode = {
        id,
        type: 'default',
        data: { label: `${key} {}` },
        position: { x: currentX, y: currentY },
        style: getNodeStyle('object')
      };
      nodes.push(objectNode);
      
      const childNodes = convertJsonToNodes(
        value,
        prefix,
        id,
        { x: currentX + 200, y: currentY }
      );
      nodes.push(...childNodes);
      currentY += Object.keys(value).length * 50 + 50;
      return;
    }

    // 处理基本类型
    nodes.push({
      id,
      type: 'default',
      data: { label: `${key}: ${formatValue(value)}` },
      position: { x: currentX, y: currentY },
      style: getNodeStyle(typeof value)
    });
    currentY += 50;
  }

  if (typeof json === 'object' && json !== null) {
    Object.entries(json).forEach(([key, value]) => {
      processValue(key, value, position.x);
    });
  }

  return nodes;
}

// 格式化值的显示
function formatValue(value) {
  if (typeof value === 'string') return `"${value}"`;
  return String(value);
}

// 获取节点样式
function getNodeStyle(type) {
  const baseStyle = {
    padding: 10,
    fontSize: '14px',
    height: '40px',
    display: 'flex',
    alignItems: 'center',
    borderRadius: '3px',
    border: '1px solid #ccc',
    background: '#fff',
  };

  switch (type) {
    case 'string':
      return { ...baseStyle, borderColor: '#4CAF50' };
    case 'number':
      return { ...baseStyle, borderColor: '#2196F3' };
    case 'boolean':
      return { ...baseStyle, borderColor: '#FF9800' };
    case 'object':
      return { ...baseStyle, borderColor: '#9C27B0', fontWeight: 'bold' };
    case 'array':
      return { ...baseStyle, borderColor: '#E91E63', fontWeight: 'bold' };
    case 'null':
      return { ...baseStyle, borderColor: '#9E9E9E', fontStyle: 'italic' };
    default:
      return baseStyle;
  }
}

export function createStructureEdges(json, prefix) {
  const edges = [];
  let lastSiblingId = null;

  // 检查是否是 X 输入的前缀（A、B、C等）
  const isXInput = /^[A-Z]$/.test(prefix);

  function processValue(key, value, parentKey, level = 0) {
    const id = parentKey ? `${parentKey}.${key}` : `${prefix}.${key}`;

    // 添加与父节点的连接
    if (parentKey) {
      edges.push({
        id: `structure-parent-${parentKey}-${id}`,
        source: parentKey,
        target: id,
        type: 'structure',
        animated: false,
        style: { 
          stroke: '#1a73e8', 
          strokeWidth: 1,
          zIndex: -1
        }
      });
    }

    // 只有在不是 X 输入或者在同一个 X 输入内部时才添加同级连线
    if (lastSiblingId && parentKey && 
        (!isXInput || (lastSiblingId.charAt(0) === id.charAt(0)))) {
      edges.push({
        id: `structure-sibling-${lastSiblingId}-${id}`,
        source: lastSiblingId,
        target: id,
        type: 'structureSibling',
        animated: false,
        style: { 
          stroke: '#1a73e8', 
          strokeWidth: 1,
          strokeDasharray: '3 3',
          zIndex: -2
        }
      });
    }

    lastSiblingId = id;

    if (typeof value === 'object' && value !== null) {
      const childLastSiblingId = lastSiblingId;
      lastSiblingId = null;
      
      Object.entries(value).forEach(([childKey, childValue]) => {
        processValue(childKey, childValue, id, level + 1);
      });
      
      lastSiblingId = childLastSiblingId;
    }
  }

  // 重置 lastSiblingId 并处理顶层节点
  lastSiblingId = null;
  if (typeof json === 'object' && json !== null) {
    Object.entries(json).forEach(([key, value]) => {
      processValue(key, value, prefix);
    });
  }

  return edges;
} 